package 尚硅谷;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangmin
 * @create 2022-03-31 16:35
 */
public class Product_Consumer_ReentrantLock {
    private static int data=5;
    private static ReentrantLock lock=new ReentrantLock();
    private static Condition condition=lock.newCondition();

    public static void product() throws InterruptedException {
        lock.lock();
        try {
            //1、判断
            while (data>=5){
                //等待，不能生产
                condition.await();
            }
            //2、干活
            data++;
            System.out.println(Thread.currentThread().getName()+"\t"+data);
            //3、通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void consumer() throws InterruptedException {
        lock.lock();
        try {
            //1、判断
            while (data<0){
                //等待，不能消费
                condition.await();
            }
            //2、干活
            data--;
            System.out.println(Thread.currentThread().getName()+"\t"+data);
            //3、通知唤醒
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                try {
                    product();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"A").start();
        }
        Thread.sleep(300);
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"B").start();
        }
        Thread.sleep(300);
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                try {
                    product();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"C").start();
        }
    }
}
